package com.mediacloud.app.newsmodule.view

import android.app.Activity
import android.content.Context
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.mediacloud.app.assembly.util.*
import com.mediacloud.app.model.interfaces.IPermissionsAgree
import com.mediacloud.app.model.interfaces.PermissionUtil
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.share.SocialShareControl
import com.mediacloud.app.share.view.SharePopGridWindow
import com.utils.RxUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.json.JSONObject
import java.io.File
import java.text.DecimalFormat

//直接分享图片 不显示出来。
class MicPosterShareGridPop(context: Context) : SharePopGridWindow(context) {
    var ticketView: View? = null
    var disposable: Disposable? = null
    override fun getResLayoutId(): Int {
        return R.layout.popwin_share_mic
    }


    init {
        ticketView = findViewById(R.id.ticketView)
        RxUtils.rxClick(findViewById(R.id.clickView)){

        }

    }

    fun saveImage(context: Context) {
        PermissionUtil.invokeStoragePermission(
            context as FragmentActivity,
            object : IPermissionsAgree {
                override fun onAgree() {
                    save()
                }

                override fun onRefuse() {
                    dismiss()
                }

                override fun hasPermissions() {
                    save()
                }
            })

    }

    override fun dismiss() {
        disposable?.dispose()
        super.dismiss()
    }

    private fun save() {
        doAsync {
            val bitmap = BitmapUtil.convertViewToBitmap(ticketView)
            val path = FileUtil.getPhotoApp() + "/" + System.currentTimeMillis() + ".jpg"
            FileUtil.saveBitmap(path, bitmap)
            uiThread {
                val file = File(path)
                Utility.insertIntoMediaStore(contentView.context, false, file, file.lastModified())
                toastCenter(contentView.context, "图片保存成功")
                dismiss()
                bitmap?.recycle()
            }
        }
    }

    override fun show(activity: Activity?) {
        super.show(activity)
    }

    fun shareImage(context: Context, share_media: Int) {
        PermissionUtil.invokeStoragePermission(context as FragmentActivity,object :IPermissionsAgree{
            override fun onAgree() {
                realShare(context, share_media)
            }

            override fun onRefuse() {
            }

            override fun hasPermissions() {
                realShare(context, share_media)
            }
        })
    }

    private fun realShare(context: Context, share_media: Int) {
        doAsync {
            val bitmap = BitmapUtil.convertViewToBitmap(ticketView)
            val path = FileUtil.saveShareBitmap(bitmap)
            uiThread {
                SocialShareControl.share(ViewUtils.searchTintContextHostActivity(context), share_media, path)
                SocialShareControl.addSocialShareListener(object : SocialShareControl.SocialShareListener {

                    override fun shareComplete(p0: Int, p1: HashMap<String, Any>?) {
                        dismiss()
                        SocialShareControl.removeSocialShareListener(this)
                    }

                    override fun shareCancel(p0: Int) {
                        dismiss()
                        SocialShareControl.removeSocialShareListener(this)
                    }

                    override fun shareError(p0: Int, p1: String?) {
                        dismiss()
                        SocialShareControl.removeSocialShareListener(this)
                    }

                })
            }
        }
    }

    fun setData(item: ArticleItem) {
        val titleTv: TextView = findViewById(R.id.titleTv)
        val startTimeTv: TextView = findViewById(R.id.startTimeTv)
        val hitCountTv: TextView = findViewById(R.id.hitCountTv)
        val qrCodeIv: ImageView = findViewById(R.id.qrCodeIv)
        val logoIv: ImageView = findViewById(R.id.logoIv)

//        logoIv.loadSrc2(
//            item.logo,
//            context.resources.getDimensionPixelSize(R.dimen.dimen3),
//            AppFactoryGlobalConfig.getDefaultImageLoadDrawable()
//        )
        loadX(context, buildUrl(3, item.logo), 1, object : RequestListener<Drawable> {
            override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                return true
            }

            override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                logoIv.setImageDrawable(resource)
                logoIv.visibility = View.VISIBLE
                return true
            }
        })
        if(!TextUtils.isEmpty(item.shareTitle)){
            titleTv.text = item.shareTitle
        }else{
            titleTv.text = item.title
        }

        var qrCode = QRCodeUtil.createQRImage("${item.url}", qrCodeIv.width, qrCodeIv.height, null)
        qrCodeIv.setImageBitmap(qrCode)

        /*item.orginDataObject?.optJSONObject("AppCustomParams")
            ?.optJSONObject("movie")?.apply {
                startTimeTv.text = optString("startTime_format")
            }*/
        if (!TextUtils.isEmpty(item.appCustomParams)){
            val jsonObject  = JSONObject(item.appCustomParams)
            jsonObject.optJSONObject("movie")?.apply {
                startTimeTv.text = optString("startTime")
            }
        }

        disposable = DataInvokeUtil.ziMeiTiApi.getAppointmentCount(6, "${item?.id}")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (it.optBoolean("state")) {
                    it.optJSONObject("data")?.optInt("counts")?.let {

                        val decimalFormat = DecimalFormat("00000000")
                        val numFormat: String = decimalFormat.format(item.hitCount)
                        hitCountTv.text = "NO.$numFormat"
                    }
                }
            }
    }
}